package com.toymate.modules.iot.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.toymate.modules.iot.entity.IotDevice;
import com.toymate.modules.iot.entity.IotProduct;
import com.toymate.modules.iot.mapper.IotDeviceMapper;
import com.toymate.modules.iot.service.IotDeviceService;
import com.toymate.modules.iot.service.IotProductService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * IotDeviceServiceImpl
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class IotDeviceServiceImpl extends ServiceImpl<IotDeviceMapper, IotDevice> implements IotDeviceService {

    private final IotProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertDeviceAuto(String serialNumber, String productId) {
        // 设备编号唯一检查
        long count = this.count(Wrappers.<IotDevice>lambdaQuery().eq(IotDevice::getSerialNumber, serialNumber));
        if (count != 0) {
            log.error("设备编号：" + serialNumber + "已经存在了，新增设备失败");
            return false;
        }
        IotDevice device = new IotDevice();
        device.setSerialNumber(serialNumber);
        device.setFirmwareVersion(BigDecimal.valueOf(1.0));
        // 设备状态（1-未激活，2-禁用，3-在线，4-离线）
        device.setStatus(1);
        device.setActiveTime(DateUtil.date());
        int random = (int) (Math.random() * (90)) + 10;
        IotProduct iotProduct = productService.getById(productId);
        if (iotProduct == null) {
            log.error("自动添加设备时，根据产品ID查找不到对应产品");
            return false;
        }
        device.setDeviceName(iotProduct.getProductName() + random);
        device.setProductId(iotProduct.getProductId());
        device.setProductName(iotProduct.getProductName());
        return this.save(device);
    }
}
